<template>
  <div id="target"></div>
  <div
    ref="contanerRef"
    class="h-screen w-screen"
    :class="{ 'overflow-hidden': isVisiblePins }"
  >
    <van-pull-refresh
      :disabled="disabledRefresh"
      v-model="refreshLoading"
      head-height="60"
      pull-distance="120"
      @refresh="handleRefresh"
      style="min-height: 100vh"
    >
      <m-infinite-list
        :isFinished="isFinished"
        :isLoading="isLoading"
        @onload="handleOnloadData"
      >
        <div v-for="(item, index) in examList" :key="index">
          <exam-item
            :exam="item"
            @dicom="handleDicom"
            @report="handleReport"
            @examDetail="handleGoExamDetail"
          ></exam-item>
        </div>
        <!-- 响应式内容展示 -->
        <transition
          :css="false"
          @before-enter="beforeEnter"
          @enter="enter"
          @leave="leave"
        >
          <pins :isVisable="isVisiblePins" :currentPins="currentPins"></pins>
        </transition>
        <div
          v-if="!examList?.length"
          class="text-center text-lg text-[#707070]"
        >
          <m-svg-icon class="w-20 h-20 mx-auto" name="no-result"></m-svg-icon>
          <span>没有相关记录</span>
        </div>
      </m-infinite-list>
    </van-pull-refresh>
  </div>
  <!-- 搜索icon -->
  <div
    class="fixed backdrop-blur bottom-20 right-3 w-5 h-5 flex justify-center items-center rounded-xl"
  >
    <m-svg-icon
      class="w-2 h-2 mx-auto"
      name="search"
      @click="handleShowPopup"
    ></m-svg-icon>
  </div>
  <van-popup
    closeable
    v-model:show="showPopup"
    position="bottom"
    :style="{
      padding: '14px',
      borderTopLeftRadius: '25px',
      borderTopRightRadius: '25px'
    }"
  >
    <van-form @submit="handleSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.StartExamDate"
          is-link
          readonly
          name="datePicker"
          label="开始时间"
          placeholder="点击选择开始时间"
          @click="showPickerStartTime = true"
        />
        <van-popup v-model:show="showPickerStartTime" position="bottom">
          <van-date-picker
            @confirm="handleConfirmStartTime"
            @cancel="showPickerStartTime = false"
          />
        </van-popup>
        <van-field
          v-model="form.EndExamDate"
          is-link
          readonly
          name="datePicker"
          label="结束时间"
          placeholder="点击选择结束时间"
          @click="showPickerEndTime = true"
        />
        <van-popup v-model:show="showPickerEndTime" position="bottom">
          <van-date-picker
            @confirm="handleConfirmEndTime"
            @cancel="showPickerEndTime = false"
          />
        </van-popup>
        <van-field
          v-model="form.Name"
          name="姓名"
          label="姓名"
          placeholder="请填写姓名"
        />
        <van-field
          v-model="form.OutPatientNo"
          name="门诊号"
          label="门诊号"
          placeholder="请填写门诊号"
        />
        <van-field
          v-model="form.InPatientNo"
          name="住院号"
          label="住院号"
          placeholder="请填写住院号"
        />
        <van-field
          v-model="form.OldDocID"
          name="影像号"
          label="影像号"
          placeholder="请填写影像号"
        />
        <van-field
          v-model="form.SickBedNo"
          name="床位号"
          label="床位号"
          placeholder="请填写床位号"
        />
        <van-field
          v-model="checkTypecolumns[selectedCheckTypeIndexes].text"
          name="picker"
          is-link
          readonly
          clearable
          label="检查类型"
          placeholder="请选择检查类型"
          @click="handleShowCheckOrDeptType('check')"
        />
        <van-field
          v-model="deptTypecolumns[selectedDeptTypeIndexes].text"
          is-link
          readonly
          label="送检科室"
          placeholder="请填写送检科室"
          @click="handleShowCheckOrDeptType('dept')"
        />
        <van-field
          v-model="form.FromDocName"
          name="送检医生"
          label="送检医生"
          placeholder="请填写送检医生"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </van-popup>
  <van-popup v-model:show="showCheckOrDeptType" position="bottom">
    <van-picker
      @confirm="handleSelectCheck"
      :columns="
        currentPickerType === 'check' ? checkTypecolumns : deptTypecolumns
      "
      @cancel="showCheckOrDeptType = false"
    />
  </van-popup>
</template>
<script setup lang="ts">
import { Ref, ref } from 'vue'
import { PartialForm } from './service/index'
import { useEventListener } from '@vueuse/core'
import gsap from 'gsap'
import examStore from '@/store/exam/index'
import homeService from './service/index'
import objUtil from '@/utils/objUtil'
import dateUtil from '@/utils/dateUtil'
import examItem from './components/ExamItem/index.vue'
import pins from '@/views/pins/index.vue'
import useDiocmHooks from '@/hooks/useDiocmHooks'

type TweenTarget = string | object | null
type Callback = (...args: any[]) => void | null
interface CurrentPins {
  id: string
  moduleName: string
  localtion: {
    translateX: number
    translateY: number
  }
}

const store = examStore()
const { deepClone } = objUtil
const { getDateRange } = dateUtil
const { findDiocmView } = useDiocmHooks
const {
  findExamList,
  handleOnloadData,
  examList,
  isFinished,
  isLoading
} = homeService
const isVisiblePins = ref(false)
const showPopup = ref(false)
const startTime = ref('')
const endTime = ref('')
const showCheckOrDeptType = ref(false)
const showPickerStartTime = ref(false)
const showPickerEndTime = ref(false)
const refreshLoading = ref(true)
const form: Ref<PartialForm> = ref({})
const contanerRef: Ref<HTMLElement | null> = ref(null)
const disabledRefresh = ref(false)
const currentPins = ref<CurrentPins>({
  id: '',
  moduleName: '',
  localtion: {
    translateX: 0,
    translateY: 0
  }
})
const checkTypecolumns = ref([
  { text: '不限', value: '' },
  { text: '超声', value: 'UIS' },
  { text: '放射', value: 'RIS' },
  { text: '内镜', value: 'EIS' },
  { text: '检验', value: 'LIS' },
  { text: '病理', value: 'PIS' }
])
const deptTypecolumns = ref([
  { text: '不限', value: '' },
  { text: '骨科', value: '骨科' },
  { text: '急诊', value: '急诊' },
  { text: '妇科', value: '妇科' },
  { text: '产科', value: '产科' },
  { text: '儿科', value: '儿科' },
  { text: '五官科', value: '五官科' },
  { text: '外科', value: '外科' },
  { text: '内科', value: '内科' },
  { text: '眼科', value: '眼科' },
  { text: 'ICU', value: 'ICU' },
  { text: '放射科', value: '放射科' },
  { text: '病理科', value: '病理科' },
  { text: '内镜科', value: '内镜科' },
  { text: '系统科', value: '系统科' }
])
let selectedCheckTypeIndexes = ref(0)
let selectedDeptTypeIndexes = ref(0)
let currentPickerType = ref('')

const initTime = async () => {
  const data = new Date()
  const [start, end] = getDateRange(data, 7, true)
  form.value = {
    StartExamDate: (startTime.value = start),
    EndExamDate: (endTime.value = end)
  }
  await findExamList(form.value)
  await handleOnloadData()
  refreshLoading.value = true
}
initTime()

const handleSubmit = () => {
  const formClone: PartialForm = deepClone(form.value)
  findExamList(formClone)
  showPopup.value = false
}
const handleConfirmStartTime = (value: any) => {
  const { selectedValues } = value
  form.value.StartExamDate = `${selectedValues[0]}-${selectedValues[1]}-${selectedValues[2]}`
  showPickerStartTime.value = false
}
const handleConfirmEndTime = (value: any) => {
  const { selectedValues } = value
  form.value.EndExamDate = `${selectedValues[0]}-${selectedValues[1]}-${selectedValues[2]}`
  showPickerEndTime.value = false
}
const handleShowPopup = () => {
  console.log(contanerRef.value)

  showPopup.value = true
}
const handleRefresh = async () => {
  await findExamList(form.value)
  refreshLoading.value = false
}
const handleDicom = async (value: any) => {
  const { id, moduleName } = value
  await findDiocmView(id, moduleName)
}
const handleGoExamDetail = (value: any) => {
  console.log(value)
  isVisiblePins.value = true
  disabledRefresh.value = true
  currentPins.value = {
    id: value.exam.id,
    moduleName: value.exam.moduleName,
    localtion: value.localtion
  }
  // LIS
  history.pushState(
    null,
    null,
    `/${value.exam.moduleName === 'LIS' ? 'checkLIS' : 'examDetail'}/${
      value.exam.moduleName
    }/${value.exam.id}`
  )
}
const handleSelectCheck = (event: any) => {
  if (currentPickerType.value === 'check') {
    form.value.ModuleName = event.selectedOptions[0].value
    selectedCheckTypeIndexes.value = event.selectedIndexes[0]
  } else {
    form.value.FromDeptName = event.selectedOptions[0].value
    selectedDeptTypeIndexes.value = event.selectedIndexes[0]
  }
  showCheckOrDeptType.value = false
}
const handleReport = () => {
  console.log('handleReport')
}
useEventListener(window, 'popstate', () => {
  isVisiblePins.value = false
  disabledRefresh.value = false
})
const beforeEnter = (el: TweenTarget) => {
  console.log(currentPins.value.localtion?.translateX)

  gsap.set(el, {
    scaleX: 0,
    scaleY: 0,
    transformOrigin: '0 0',
    translateX: currentPins.value.localtion?.translateX,
    translateY: currentPins.value.localtion?.translateY,
    opacity: 0
  })
}
const enter = (el: TweenTarget, done: Callback) => {
  gsap.to(el, {
    duration: 0.3,
    scaleX: 1,
    scaleY: 1,
    opacity: 1,
    translateX: 0,
    translateY: 0,
    onComplete: done // 结束callback
  })
}
const leave = (el: TweenTarget, done: Callback) => {
  gsap.to(el, {
    duration: 0.3,
    scaleX: 0,
    scaleY: 0,
    translateX: currentPins.value.localtion?.translateX,
    translateY: currentPins.value.localtion?.translateY,
    onComplete: done // 结束callback
  })
}
const handleShowCheckOrDeptType = (type: string) => {
  currentPickerType.value = type
  showCheckOrDeptType.value = true
}
</script>
